import React, { useState, useEffect } from 'react'
import Taro, { useRouter, useDidShow } from '@tarojs/taro'
import { View, Picker  } from '@tarojs/components'
import { AtInput, AtButton, AtMessage, AtList, AtListItem } from 'taro-ui'
import { request } from '@/utils'
import './index.less'


const StaffEdit = () => {
  const router = useRouter()
  const { params } = router
  const [name, setName] = useState(params?.name || '')
  const [account, setAccount] = useState(params?.account || '')
  const [pwd, setPwd] = useState(params?.pwd || '')
  const [supplierId, setSupplierId] = useState(params?.supplierId || '')
  const [supplierList, setSupplierList] = useState([])
  const [supplierName, setSupplierName] = useState('请选择撬装站')
  const getSuppliers = async () => {
    const {list} = await request({url: 'hkshihua/user/supplier/list'})
    setSupplierList(list)
  }
  const handleChange = (e, type) => {
    switch(type) {
      case 1:
        setName(e)
        break;
      case 2:
        setAccount(e)
          break;
      case 3:
        setPwd(e)
        break;
      case 4:
        setSupplierId(e)
        break;
    }
  }
  const handleDel = async () => {
    Taro.showLoading({mask: true})
    const { error } = await request({ url: 'hkshihua/user/deleteUser', data: {userId: params.userId}})
    if (error) return
    Taro.atMessage({ message: '删除成功', type: 'success'})
    Taro.navigateBack()
  }
  const handleSave = async () => {
    if(!name) {
      Taro.atMessage({message: '请输入姓名', type: 'error'})
      return
    }
    if(!account) {
      Taro.atMessage({message: '请输入账号', type: 'error'})
      return
    }
    if(!pwd) {
      Taro.atMessage({message: '请输入密码', type: 'error'})
      return
    }
    if(!supplierId) {
      Taro.atMessage({message: '请选择撬装', type: 'error'})
      return
    }
    if(params.userId) {
      Taro.showLoading({mask: true})
     const {error} = await request({ url: 'hkshihua/operator/addOrUpdateOperator', header: {"Content-Type": "application/json"},method: 'POST',data: JSON.stringify({account, name, pwd, supplierId, userId: params.userId})})
     if(error) return
    } else {
      Taro.showLoading({mask: true})
      const {error} = await request({ url: 'hkshihua/operator/addOrUpdateOperator', header: {"Content-Type": "application/json"},method: 'POST',data: JSON.stringify({account, name, pwd, supplierId})})
      if(error) return
    }
    Taro.atMessage({ message: '保存成功', type: 'success'})
    Taro.navigateBack()
  }
  useDidShow(() => {
    getSuppliers()
  })
  useEffect(() => {
    const data = supplierList.find((item) => item.id == supplierId)
    if(data) {
      setSupplierName(data.name)
    }
  }, [supplierList, supplierId])
  const handlePickChange = (e) => {
    const { detail: { value }} = e
    setSupplierName(supplierList[value].name)
    setSupplierId(supplierList[value].id)
  }
  return (
    <View>
      <AtMessage />
      <View className='edit'>
        <AtInput cursor={-1} title='姓名' name='name' type='text' placeholder='请输入姓名' value={name} onChange={(e) => handleChange(e, 1)} />
        <AtInput cursor={-1} title='账号' name='account' type='text' placeholder='请输入账号' value={account} onChange={(e) => handleChange(e, 2)} />
        <AtInput cursor={-1} title='密码' name='pwd' type='password' placeholder='请输入密码' value={pwd} onChange={(e) => handleChange(e, 3)} />
        <Picker onChange={handlePickChange} mode='selector' range={supplierList} rangeKey='name' >
          <AtList>
            <AtListItem
              title='撬装站'
              extraText={supplierName}
            />
          </AtList>
        </Picker>
      </View>
      <View className='btn'>
        {params.userId && <AtButton type='primary' full onClick={handleDel} className='del-btn'>删除员工</AtButton>}
        <AtButton type='primary' full onClick={handleSave}>保存</AtButton>
      </View>
    </View>
  )
}

export default StaffEdit
